﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Bes.Swsp.ToolBox
{
  public class Logger
  {
    private static TextWriterTraceListener _listener;
    private static bool _logging = false;

    public static string LogFile { get; set; }

    public static bool IsLogging
    {
      get
      {
        return _logging;
      }
    }

    static Logger()
    {
      string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      string tempDir = System.IO.Path.Combine(documents, "temp");
      Directory.CreateDirectory(tempDir);

      LogFile = System.IO.Path.Combine(tempDir, "Swsp.Toolbox.log");
    }

    public static void StartLogging()
    {
      _logging = true;

      if (_listener == null)
      {
        _listener = new TextWriterTraceListener(LogFile);
        Trace.Listeners.Add(_listener);
        Trace.AutoFlush = true;
      }
    }

    public static void StopLogging()
    {
      _logging = false;

      if (_listener != null)
      {
        Trace.Flush();
        Trace.Listeners.Remove(_listener);
        _listener.Close();
        _listener = null;
      }
    }

    public static void Log(string message)
    {
      if (_logging)
      {
        Trace.WriteLine(DateTime.Now.ToString() + " - " + message);

        OnLogged(new LoggerEventArgs(message));          
      }
    }

    public static event EventHandler<LoggerEventArgs> Logged;

    protected static void OnLogged(LoggerEventArgs eventArgs)
    {
      if (Logged != null)
      {
        Logged(null, eventArgs);
      }      
    }
  }

  public class LoggerEventArgs : EventArgs
  {
    public LoggerEventArgs(string message)
    {
      Message = message;
    }

    public string Message { get; set; }
  }

}
